'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url admin/pages/files_mzgl/page_binding/kh/add_aidbind 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			schema_bind_type,
			album_id,
			tv_name,
			_id,
			path,
			app_access_token,
			app_id,
			appname
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------


		console.log("data=======", data);





		// 去数据库匹配
		let A = await vk.baseDao.selects({
			dbName: "dy_tv_series",
			pageIndex: 1,
			pageSize: -1,
			// 主表where条件
			whereJson: {
				tv_id: _id
			},
			fieldJson: {
				episode_id: true,
				seq: true,
				tv_id: true,
				ma_app_id: true
			},
		});

		console.log("A===", A.rows);

		const arr = A.rows
		// 获取送审的小程序
		const ma_app_id = arr[0].ma_app_id
		// 获取APP秘钥
		let appInfo = await db.collection('a_appid').where({
			appid: ma_app_id
		}).get()
		let appsecret = appInfo.data[0].appsecret
		let urlA = "https://open.douyin.com/oauth/client_token/"
		const accessToken = await uniCloud.httpclient.request(urlA, {
			method: 'POST',
			headers: {
				"Content-Type": "application/json",
			},
			data: {
				client_key: ma_app_id, // id
				client_secret: appsecret, // 密钥
				grant_type: "client_credential",
			},
			dataType: 'json', // 指定返回值为json格式，自动进行parseK
		})


		// 有效时间为 2 个小时
		let access_token = accessToken.data.data.access_token

		console.log("access_token===", access_token);


		if (!arr[0].episode_id) {
			return {
				code: 1,
				msg: "剧集id为空，请编辑短剧"
			}
		}
		let schema_bind_list = []
		for (let i = 0; i < arr.length; i++) {
			const tv_id = arr[i].tv_id
			const series = String(arr[i].seq)
			console.log("series====", series);
			const episode_id = arr[i].episode_id
			schema_bind_list.push({
				album_id: album_id,
				episode_id: episode_id,
				path: path,
				params: [{
						key: "tv_id",
						value: tv_id
					},
					{
						key: "series",
						value: series
					},
				]
			})




		}
		try {
			const results = await Promise.allSettled(
				app_id.map(async (item) => {
					let urlT = "https://open.douyin.com/api/playlet/v2/album/bind/";
					let resA = await uniCloud.httpclient.request(urlT, {
						method: "POST",
						headers: {
							"Content-Type": "application/json",
							"access-token": access_token,
						},
						data: {
							schema_bind_type: 2,
							app_id: item,
							schema_bind_list: schema_bind_list,
						},
						dataType: "json",
					});
					console.log("resA====", resA);
					if (resA.data.err_msg) {
						return {
							code: 1,
							msg: resA.data.err_msg,
						};
					}
					return {
						code: 0,
						msg: "success"
					};
				})
			);

			for (const result of results) {
				if (result.status === "rejected" || result.value.code === 1) {
					return result.value;
				}
			}
		} catch (error) {
			console.error("Error:", error);
			return {
				code: -1,
				msg: "An error occurred"
			};
		}
		// 信息存入数据库
		let id = await vk.baseDao.add({
			dbName: "dy_ymbd",
			dataJson: {
				schema_bind_type: 2,
				app_id: app_id,
				album_id: album_id,
				path: path,
				appname,
				key1: "tv_id",
				key2: "series",
				tv_name: tv_name,
				series: arr.length,
				_add_time_str: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss")
			}
		})
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}